use std::env;

use diesel::{
    prelude::*,
    r2d2::{ConnectionManager, Pool, PoolError, PooledConnection},
};
use dotenv::dotenv;
use once_cell::sync::OnceCell;
//mysql 的池化链接
type PgPool = Pool<ConnectionManager<MysqlConnection>>;
pub static DB_POOL: OnceCell<PgPool> = OnceCell::new();

pub fn try_connect() -> Result<PooledConnection<ConnectionManager<MysqlConnection>>, PoolError> {
    DB_POOL.get().unwrap().get()
}
pub fn build_pool(database_url: &str, size: u32) -> Result<PgPool, PoolError> {
    //连接管理
    //min_idle 池中最大的可停留连接数
    let manager = ConnectionManager::<MysqlConnection>::new(database_url);
    let res = diesel::r2d2::Pool::builder()
        .max_size(size)
        .min_idle(Some(size))
        .test_on_check_out(false)
        .idle_timeout(None)
        .max_lifetime(None)
        .build(manager);
    res
}
pub fn create_mysql_connect_pool() {
    dotenv().ok();
    let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
    DB_POOL
        .set(
            build_pool(database_url.as_str(), 10)
                .expect(&format!("Error connecting to {}", &database_url)),
        )
        .ok();
}
